package com.the475group.obd;

import java.io.IOException;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

import com.the475group.obd.impl.OBDConnectionListener;


public class OBDConnection extends Thread {
	
	private final BluetoothSocket socket;
    private OBDConnectionListener listener;
    private static final String TAG = "OBDConnection"; 
    
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
 
    public OBDConnection (BluetoothDevice device, OBDConnectionListener listener) {
        BluetoothSocket tmp = null;
        
        this.listener = listener;
        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
        	Log.e(TAG,"Error on trying to create socket to service record (constructor method)");
        	e.printStackTrace();
        }
        socket = tmp;
    }
 
    public void run() {
    	BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    	if(mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()){
    		mBluetoothAdapter.cancelDiscovery();
    		 
            try {
                socket.connect();
            } catch (IOException connectException) {
            	Log.e(TAG,"Error on trying to connect socket (run method)");
                cancel();
                return;
            }
            
            listener.onConnected(socket);
            
    	} else {
    		Log.e(TAG,"BluetoothAdapter is null or is not enabled (run method)");
    		return;
    	}
        
    }
 
    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
        	Log.d(TAG,"canceling...");
            socket.close();
            listener.onDisconnected();
        } catch (IOException e) {
        	Log.d(TAG,"Error on closing socket (cancel method)");
        	e.printStackTrace();
        }
    }
	
}
